<template>
  <div class="comment_on">
    <Form class="pb70" @failed="onFailed" @submit="onSubmit">
      <!-- 评分 -->
      <CellGroup>
        <div v-if="commentDetail.isScore === 'Y'" class="mb8">
          <div
            v-for="item in 10"
            v-show="commentDetail['scoreTitle' + item]"
            :key="item"
          >
            <Field
              :label="commentDetail['scoreTitle' + item]"
              :rules="[
                {
                  required: !!commentDetail['scoreTitle' + item],
                  message: '请给' + commentDetail['scoreTitle' + item] + '打分',
                },
              ]"
              name="rate"
            >
              <template #input>
                <Rate
                  v-model="pageForm['score' + item + 'Value']"
                  :icon="commentDetail['scoreType' + item]"
                  :size="18"
                  :void-icon="
                    commentDetail['scoreType' + item] === 'smail'
                      ? 'smile'
                      : commentDetail['scoreType' + item]
                  "
                  color="#ffd21e"
                  void-color="#eee"
                />
                <template v-if="showY(item)">{{ showY(item) }}</template>
                <template v-else>
                  <span class="fw500 f17 ml10">{{
                      pageForm["score" + item + "Value"]
                    }}</span
                  ><span v-show="pageForm['score' + item + 'Value']" class="f12"
                >分</span
                >
                </template>
              </template>
            </Field>
          </div>
        </div>
      </CellGroup>
      <!-- 点评文字 -->
      <div v-if="commentDetail.isText === 'Y'" class="comment_content">
        <Field
          v-model="pageForm.textComment"
          :maxlength="textLength"
          autosize
          class="comment_text_field"
          label=""
          label-align="top"
          placeholder="请输入内容"
          rows="4"
          show-word-limit
          type="textarea"
        />
      </div>
      <!-- 照片上传 -->
      <div
        v-if="commentDetail.isPicture === 'Y'"
        class="comment_content comment_photo"
      >
        <Uploader
          v-model="fileList"
          :max-count="picMaxCount"
          :max-size="picMaxSize"
          multiple
          @oversize="onOversize"
        />
        <p class="desc" @click="showVConsole">
          <span v-if="commentDetail.pictureLimit" class="f12"
          >可上传{{ picMaxCount }}张照片，</span
          >
          <span v-if="commentDetail.pictureSize" class="f12"
          >且每张照片不超过{{ commentDetail.pictureSize }}M</span
          >
        </p>
      </div>
      <!-- 提交按钮 -->
      <div class="comment_content sub_btn">
        <van-button
          :disabled="loading"
          :loading="loading"
          block
          native-type="submit"
          type="primary"
        >
          提交
        </van-button>
      </div>
    </Form>
  </div>
  <!-- 不能点评的提示 -->
  <Popup
    v-model:show="status.showError"
    :close-on-click-overlay="false"
    :overlay-style="{ background: '#fff' }"
    round
  >
    <Empty :description="status.msg" class="empty" image-size="100" />
  </Popup>
</template>

<script setup>
import { getDetail, saveComment } from "@/server/business/comment.js";
import { apiCheckToken } from "@/server/business/survey.js";
import { uploadFile } from "@/server/common/file.js";
import { setWeappToken } from "@/utils/auth.js";
import {
  getDeviceInfo,
  getUrlQuery,
  goWxLogin,
  dispatchToWechat,
  showVConsole,
  getSource,
  wxPageRedirect
} from "@/utils/common.js";
import { CellGroup, Empty, Field, Form, Popup, Rate, showSuccessToast, showToast, Uploader } from "vant";
import { computed, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";

const useQuery = getUrlQuery(); // url获取数据
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const fileList = ref([]);
let userInfo = {};
const status = reactive({
  showError: false,
  msg: ""
});
const pageForm = reactive({
  appraiseId: route.query.id,
  subjectId: route.query.subjectId || "",
  subjectId1: route.query.subjectId1 || "",
  subjectId2: route.query.subjectId2 || "",
  subjectId3: route.query.subjectId3 || "",
  subjectId4: route.query.subjectId4 || "",
  subjectId5: route.query.subjectId5 || "",
  subjectId6: route.query.subjectId6 || "",
  textComment: "",
  score1Value: "",
  score1Comment: "",
  score2Value: "",
  score2Comment: "",
  score3Value: "",
  score3Comment: "",
  score4Value: "",
  score4Comment: "",
  score5Value: "",
  score5Comment: ""
});
const commentDetail = reactive({});
// 点评文字长度
const textLength = computed(() => {
  return commentDetail.textLength || commentDetail.textLength === 0
    ? commentDetail.textLength
    : null;
});
// 点评图片数量限制
const picMaxCount = computed(() => {
  return commentDetail.pictureLimit || commentDetail.pictureLimit === 0
    ? commentDetail.pictureLimit
    : Infinity;
});
// 点评图片大小限制
const picMaxSize = computed(() => {
  return commentDetail.pictureSize || commentDetail.pictureSize === 0
    ? commentDetail.pictureSize * 1024 * 1024
    : Infinity;
});
// 图片超出限制
const onOversize = () => {
  showToast("文件大小不能超过" + commentDetail.pictureSize + "MB");
};
// 是否展示默认打分提示
const showY = (n) => {
  if (commentDetail["appraiseScore" + n]) {
    let val =
      commentDetail["appraiseScore" + n].split("|")[
      pageForm["score" + n + "Value"] - 1
        ];
    pageForm["score" + n + "Comment"] = val;
    return val;
  } else {
    return false;
  }
};
// 上传文件
const upload = () => {
  return new Promise((resolve, reject) => {
    let pall = fileList.value.map((file) => {
      let formDate = new FormData();
      formDate.append("file", file.file || file.raw);
      return uploadFile(formDate);
    });
    Promise.all(pall)
      .then((img) => {
        let list = img.map((next) => next.data.url);
        resolve(list);
      })
      .catch((msg) => {
        reject(msg);
        loading.value = false;
      });
  });
};
// 提交
const onSubmit = async () => {
  loading.value = true;
  let imgs = await upload();
  pageForm.pictureComment = imgs.join(",^");
  pageForm.commentTime = new Date().getTime();
  pageForm.checkTokenUser = userInfo;
  pageForm.textComment = pageForm.textComment ? pageForm.textComment : "此用户未填写评价内容";
  route.query.staffUserId && (pageForm.staffUserId = route.query.staffUserId)
  saveComment(pageForm)
    .then(() => {
      showSuccessToast("点评成功！");
      dispatchToWechat(route.query.callback || "callback");
      let type = ["navigateTo", "switchTab", "reLaunch", "redirectTo"];
      for (let val of type) {
        if (route.query[val]) return wxPageRedirect(route.query[val], val);
      }
      router.back();
      loading.value = false;
    })
    .catch(() => (loading.value = false));
};
// 提交表单报错 调试用
const onFailed = (errorInfo) => {
  console.log("failed", errorInfo);
};
// 采集系统数据
const getSysData = () => {
  getSource().then((type) => {
    pageForm.appraiseSource = type || "h5";
  });
  const mobileInfo = getDeviceInfo();
  pageForm.browseType = mobileInfo.browseType;
  pageForm.deviceType = mobileInfo.model;
  pageForm.osVersion = mobileInfo.os;
};
// 根据token获取用户信息
const getUserInfo = () => {
  if (useQuery.token) {
    apiCheckToken({ memberUserToken: useQuery.token })
      .then((res) => {
        userInfo = res.data;
        if (!userInfo.pkMember) {
          status.showError = true;
          status.msg = "未获取到用户信息";
        }
      })
      .catch(() => {
        status.showError = true;
        status.msg = "未获取到用户信息";
      });
  }
};
// 初始化
const init = async () => {
  if ((!useQuery.token || ["#token%23", "#token#"].includes(useQuery.token))&&!route.query.staffUserId) {
    status.showError = true;
    status.msg = "未获取到用户信息";
    getSource().then((type) => {
      if (type === "weapp") goWxLogin(); // 没有token 小程序跳登录
    });
    return;
  }
  setWeappToken(useQuery.token); // 存储用户token 用于加入接口的header
  let res = await getDetail(route.query.id);
  Object.assign(commentDetail, res.data.appraiseConfig);
  getSysData();
  if(!route.query.staffUserId) getUserInfo();
};
init();
/**
 * userType	填写点评信息的用户账号类型staff：工会成员；member：会员；none：未识别；
 * nickName	微信昵称
 * avatar	微信头像地址
 * commentBy	点评人账户标识
 * */
</script>

<style scoped>
.comment_on {
  height: 100%;
  background: var(--van-gray-1);
  position: relative;
}

.comment_content {
  padding: 1.4rem 1.5rem;
  background: var(--van-white);
}

.comment_photo {
  margin-top: -1.4rem;
}

.comment_text_field {
  background: #f7f8fa;
}

.sub_btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}
</style>
